package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.entity.ApFollowBehavior;
import com.heima.behavior.mapper.ApFollowBehaviorMapper;
import com.heima.behavior.service.IApBehaviorEntryService;
import com.heima.behavior.service.IApFollowBehaviorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.user.dto.FollowBehaviorDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * APP关注行为表 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-01-20
 */
@Service
public class ApFollowBehaviorServiceImpl extends ServiceImpl<ApFollowBehaviorMapper, ApFollowBehavior> implements IApFollowBehaviorService {

    @Autowired
    private IApBehaviorEntryService behaviorEntryService;


    /**
     * 保存行为实体关注记录
     *
     * @param dto
     */
    @Override
    @Transactional
    public void saveFollowBehavior(FollowBehaviorDto dto) {
        //1.根据行为实体信息-查询行为实体
        ApBehaviorEntry entry = behaviorEntryService.getEntry(dto.getUserId(), dto.getEquipmentId());
        if (entry != null) {
            //2.构建关注行为实体对象，执行保存
            //2.1 查询关注行为记录是否存在，如果存在：更新操作类型

            LambdaQueryWrapper<ApFollowBehavior> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ApFollowBehavior::getEntryId, entry.getId());
            queryWrapper.eq(ApFollowBehavior::getFollowId, dto.getFollowId());
            ApFollowBehavior one = this.getOne(queryWrapper);
            if (one == null) {
                //行为实体没有关注该作者
                if (dto.getOperation().equals(0)) {
                    ApFollowBehavior followBehavior = new ApFollowBehavior();
                    followBehavior.setEntryId(entry.getId());
                    followBehavior.setFollowId(dto.getFollowId());
                    followBehavior.setOperation(dto.getOperation());
                    this.save(followBehavior);
                }
            } else {
                //行为实体以及存在操作记录， 判断当前操作类型是否跟数据库操作类型一致 不一致：更新
                if (!dto.getOperation().equals(one.getOperation())) {
                    one.setOperation(dto.getOperation());
                    this.updateById(one);
                }
            }
        }
    }
}
